using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.HtmlControls;
using System.Text;

namespace Chaks.SharePoint.jQuery
{
    public class ImageCycleWebPart : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private UserControl imageCycleControl;

        private StringBuilder cycleScriptBuilder=new StringBuilder();

        #region Constructor

        public ImageCycleWebPart()
        {
            
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the name of the library.
        /// </summary>
        /// <value>The name of the library.</value>
        public string LibraryName
        {
            get; set;
        }

        /// <summary>
        /// Gets or sets the transition.
        /// </summary>
        /// <value>The transition.</value>
        public string Transition
        {
            get; set;
        }

        /// <summary>
        /// Gets or sets the timeout.
        /// </summary>
        /// <value>The timeout.</value>
        public string Timeout
        {
            get; set;
        }

        /// <summary>
        /// Gets or sets the speed.
        /// </summary>
        /// <value>The speed.</value>
        public string Speed
        {
            get; set;
        }

        #endregion

        #region Methods

        protected override void OnPreRender(EventArgs e)
        {
            #region Build Script

            //cycleScriptBuilder.Append("<script type=\"text/javascript\">$(document).ready(function(){$('.slideshow').cycle({");

            cycleScriptBuilder.Append("<script type=\"text/javascript\">$(function(){$('.slideshow').cycle({");

            int nParsedInteger;
        
            if(!String.IsNullOrEmpty(Transition))
            {
                cycleScriptBuilder.Append(String.Format("fx: '{0}',",Transition));    
            }
            else
            {
                cycleScriptBuilder.Append("fx: 'fade',");
            }

            if (!String.IsNullOrEmpty(Timeout) && Int32.TryParse(Timeout, out nParsedInteger))
            {
                cycleScriptBuilder.Append(String.Format("timeout: {0},", Timeout));
            }
            else
            {
                cycleScriptBuilder.Append("timeout: 2000,");
            }

            if (!String.IsNullOrEmpty(Speed) && Int32.TryParse(Speed, out nParsedInteger))
            {
                cycleScriptBuilder.Append(String.Format("speed: {0}",Speed));
            }
            else
            {
                cycleScriptBuilder.Append("speed: 500");
            }

            cycleScriptBuilder.Append("});});</script>");

            #endregion

            if (!String.IsNullOrEmpty(LibraryName))
            {
                #region Get Images

                List<ImageCycle> pictures = new List<ImageCycle>();

                SPList lstPictures;

                SPSite site = SPContext.GetContext(HttpContext.Current).Site;

                using (SPWeb curWeb = site.OpenWeb())
                {

                    lstPictures = curWeb.Lists[new Guid(LibraryName)];

                    SPQuery camlQuery = new SPQuery();
                    camlQuery.ViewFields = "<FieldRef Name='Title' /><FieldRef Name='Url' />";
                    camlQuery.Query = "<OrderBy><FieldRef Name='Created' Ascending='True' /></OrderBy>";

                    SPListItemCollection lstPicturesCollection = lstPictures.GetItems(camlQuery);

                    foreach (SPListItem imageItem in lstPicturesCollection)
                    {
                        ImageCycle imageCycle = new ImageCycle
                                                    {
                                                        AltText = imageItem["Title"].ToString(),
                                                        Url = imageItem.Url
                                                    };

                        pictures.Add(imageCycle);
                    }

                }

                #endregion

                #region Set Control Values

                Literal ltlCycleScript = imageCycleControl.FindControl("ltlCycleScript") as Literal;
                ltlCycleScript.Text = cycleScriptBuilder.ToString();

                Repeater rptrPictures = imageCycleControl.FindControl("rptrPictures") as Repeater;
                rptrPictures.DataSource = pictures;
                rptrPictures.DataBind();

                HtmlAnchor anchorLibrary = imageCycleControl.FindControl("anchorLibrary") as HtmlAnchor;
                anchorLibrary.HRef = lstPictures.DefaultViewUrl;
                anchorLibrary.InnerText = String.Format("Go to {0} Library", lstPictures.Title);

                #endregion

            }

            base.OnPreRender(e);
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            imageCycleControl = Page.LoadControl("~/_controltemplates/Chaks.SharePoint.jQuery/ImageCycleControl.ascx") as UserControl;

            Controls.Add(imageCycleControl);
        }

        public override ToolPart[] GetToolParts()
        {
            ToolPart[] toolParts = new ToolPart[] { new WebPartToolPart(), new ImageCycleToolPart() };

            return toolParts;
        }

        #endregion
    }
}
